<template>
  <!-- 资产台账表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1100px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120">
      <el-row>
        <el-col :span="8">
          <el-form-item label="检具编号" prop="assetCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetCode"
              placeholder="请输入检具编号"
              clearable
            />

            <span v-else>{{ formData.assetCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="器具名称" prop="assetName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetName"
              placeholder="请输入器具名称"
              clearable
            />
            <span v-else>{{ formData.assetName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="器具类型" prop="assetTypeId">
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请选择类型"
              v-model="formData.assetTypeId"
              :data="catalogList"
              :render-after-expand="false"
              :check-strictly="true"
              node-key="id"
              :props="{
                label: 'assetTypeName',
                value: 'id',
                children: 'nodes',
              }"
              style="width: 300px"
              @node-click="handleNodeClick"
              clearable
            />
            <span v-else>{{ formData.assetTypeName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="器具状态" prop="assetStatus">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.assetStatus"
              placeholder="请选择器具状态"
              style="width: 300px"
              clearable
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('mtAssetStatus')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "mtAssetStatus",
                formData.assetStatus
              )
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格/型号" prop="assetSpecification">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetSpecification"
              placeholder="请输入规格/型号"
              clearable
            />

            <span v-else>{{ formData.assetSpecification }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="准确度等级" prop="accuracyLevel">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.accuracyLevel"
              placeholder="请输入准确度等级"
              clearable
            />

            <span v-else>{{ formData.accuracyLevel }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分度值/分辨力" prop="measuringDivision">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.measuringDivision"
              placeholder="请输入分度值/分辨力"
              clearable
            />

            <span v-else>{{ formData.measuringDivision }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="器具属性" prop="assetAttribute1">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetAttribute1"
              placeholder="请输入器具属性"
              clearable
            />

            <span v-else>{{ formData.assetAttribute1 }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制造工厂">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.makerId"
              placeholder="请选择制造工厂"
              style="width: 300px"
              clearable
              filterable
              @change="(e) => handleMakerChange(e, 'row')"
            >
              <el-option
                v-for="item in makerList"
                :key="`${item.id}`"
                :label="`${item.makerCode}-${item.makerName}`"
                :value="`${item.id}`"
              />
            </el-select>

            <span v-else
              >{{ formData.makerCode }}{{ formData.makerName ? "-" : ""
              }}{{ formData.makerName }}</span
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出厂编号">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.manufactureCode"
              placeholder="请输入出厂编号"
              clearable
            />

            <span v-else>{{ formData.manufactureCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="表头编号" prop="headerNumber">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.headerNumber"
              placeholder="请输入表头编号"
              clearable
            />

            <span v-else>{{ formData.headerNumber }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检具图号" prop="drawingNumber">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.drawingNumber"
              placeholder="请输入检具图号"
              clearable
            />

            <span v-else>{{ formData.drawingNumber }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入账日期" prop="accountDate">
            <el-date-picker
              style="width: 300px"
              v-if="!props.isReadonly"
              v-model="formData.accountDate"
              type="month"
              placeholder="请选择入账日期"
              format="YYYY/MM"
              value-format="YYYY-MM"
            />

            <span v-else>{{
              formData.accountDate
                ? dayjs(formData.accountDate).format("YYYY-MM")
                : ""
            }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="管理类别" prop="measuringType">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.measuringType"
              placeholder="请选择管理类别"
              clearable
              style="width: 300px"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'EquipmentCategory'
                )"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "EquipmentCategory",
                formData.measuringType
              )
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检定周期" prop="checkPeriod">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.checkPeriod"
              placeholder="请输入检定周期"
              clearable
            >
              <template #append>个月</template>
            </el-input>

            <span v-else>{{ formData.checkPeriod }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="到期日" prop="nextCheckDate">
            <el-date-picker
              v-if="!props.isReadonly"
              v-model="formData.nextCheckDate"
              type="date"
              placeholder="请选择到期日"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />

            <span v-else>{{
              formData.nextCheckDate
                ? dayjs(formData.nextCheckDate).format("YYYY-MM-DD")
                : ""
            }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="使用部门" prop="usingDepartmentId">
            <SelectOriganizationDangerGrant
              v-if="!props.isReadonly"
              @change="(ids:string) => getSelectIds(ids, '使用部门')"
              @change-data="(datas) => getSelectDatas(datas, '使用部门')"
              :isCheckStrictly="true"
              :isMultiple="false"
              :disabled="false"
              :data="dataObject('使用部门')"
              :selectData="formData.usingDepartmentId"
            />

            <span v-else>{{ formData.usingDepartmentName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="使用人" prop="usingPersonId">
            <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.usingPersonId"
              placeholder="请选择使用人"
              clearable
              @change="(e) => changePerson(e, '使用人')"
            >
              <el-option
                v-for="item in personList2"
                :label="`${item.firstName}`"
                :value="`${item.id}`"
              />
            </el-select>

            <span v-else>{{ formData.usingPersonName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />

            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="检定地点" prop="checkPlace">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.checkPlace"
              placeholder="请输入检定地点"
              clearable
            />

            <span v-else>{{ formData.checkPlace }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="检定人" prop="checkPerson">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.checkPerson"
              placeholder="请输入检定人"
              clearable
            />
            <span v-else>{{ formData.checkPerson }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订货号" prop="orderNumber">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.orderNumber"
              placeholder="请输入订货号"
              clearable
            />

            <span v-else>{{ formData.orderNumber }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否是固定资产" prop="isFixedAsset">
            <el-switch
              v-if="!props.isReadonly"
              v-model="formData.isFixedAsset"
              inline-prompt
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />

            <span v-else>{{ formData.isFixedAsset === 1 ? "是" : "否" }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="U9编码" prop="fixedAssetCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.fixedAssetCode"
              placeholder="请输入U9编码"
              clearable
            />

            <span v-else>{{ formData.fixedAssetCode }}</span>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="器具寿命" prop="assetLifespan">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetLifespan"
              placeholder="请输入器具寿命"
              clearable
            >
              <template #append>年</template>
            </el-input>

            <span v-else>{{ formData.assetLifespan }}</span>
          </el-form-item>
        </el-col> -->

        <!-- <el-col :span="8">
          <el-form-item label="品牌型号">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.assetModelId"
              placeholder="请选择品牌型号"
              style="width: 300px"
              clearable
              @change="handelBrandModelNo"
            >
              <el-option
                v-for="item in brandModelList"
                :key="`${item.id}`"
                :label="`${item.brandName}-${item.modelNo}`"
                :value="`${item.id}`"
              />
            </el-select>

            <span v-else
              >{{ formData.assetBrandName
              }}{{ formData.assetBrandName ? "-" : ""
              }}{{ formData.assetModelNo }}</span
            >
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="供应商" prop="supplierId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.supplierId"
              placeholder="请选择供应商"
              style="width: 300px"
              clearable
              @change="handelPartner"
            >
              <el-option
                v-for="item in mdmpartnerList"
                :key="`${item.id}`"
                :label="`${item.partnerCode}-${item.partnerName}`"
                :value="`${item.id}`"
              />
            </el-select>
            <span v-else>
              {{ formData.supplierCode }}{{ formData.supplierName ? "-" : ""
              }}{{ formData.supplierName }}</span
            >
          </el-form-item>
        </el-col> -->

        <el-col :span="24">
          <el-tabs type="border-card">
            <el-tab-pane label="器具属性">
              <el-row>
                <!-- <el-col :span="8">
                  <el-form-item label="测量精度" prop="measuringAccuracy">
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.measuringAccuracy"
                      placeholder="请输入测量精度"
                      clearable
                    />

                    <span v-else>{{ formData.measuringAccuracy }}</span>
                  </el-form-item>
                </el-col> -->

                <el-col :span="8">
                  <el-form-item label="资产原值" prop="originalValue">
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.originalValue"
                      placeholder="请输入资产原值"
                      clearable
                    />

                    <span v-else>{{ formData.originalValue }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="资产折旧价值" prop="residualValue">
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="formData.residualValue"
                      placeholder="请输入资产折旧价值"
                      clearable
                    />

                    <span v-else>{{ formData.residualValue }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <el-tab-pane label="使用情况">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="检定/校准部门" prop="repairDepartmentId">
                    <SelectOriganizationDangerGrant
                      v-if="!props.isReadonly"
                      @change="(ids:string) => getSelectIds(ids, '检定/校准部门')"
                      @change-data="
                        (datas) => getSelectDatas(datas, '检定/校准部门')
                      "
                      :isCheckStrictly="true"
                      :isMultiple="false"
                      :disabled="false"
                      :data="dataObject('检定/校准部门')"
                      :selectData="formData.repairDepartmentId"
                    />

                    <span v-else>{{ formData.repairDepartmentName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="检定/校准负责人" prop="repairManagerId">
                    <el-select
                      style="width: 100%"
                      v-if="!props.isReadonly"
                      v-model="formData.repairManagerId"
                      placeholder="请选择检定/校准负责人"
                      clearable
                      @change="(e) => changePerson(e, '检定/校准负责人')"
                    >
                      <el-option
                        v-for="item in personList1"
                        :label="`${item.firstName}`"
                        :value="`${item.id}`"
                      />
                    </el-select>

                    <span v-else>{{ formData.repairManagerName }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="器具位置" prop="locationId">
                    <el-tree-select
                      placeholder="请输入器具位置"
                      style="width: 300px"
                      filterable
                      v-if="!props.isReadonly"
                      v-model="formData.locationId"
                      :data="locationInfoTree"
                      node-key="id"
                      clearable
                      :props="{ label: 'locationName', children: 'nodes' }"
                      check-strictly
                      @node-click="changeLocation"
                      :render-after-expand="false"
                      @change="handelLocation"
                    />

                    <span v-else>{{ formData.locationName }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="管理部门" prop="manageDepartmentId">
                    <SelectOriganizationDangerGrant
                      v-if="!props.isReadonly"
                      @change="(ids:string) => getSelectIds(ids, '管理部门')"
                      @change-data="
                        (datas) => getSelectDatas(datas, '管理部门')
                      "
                      :isCheckStrictly="true"
                      :isMultiple="false"
                      :disabled="false"
                      :data="dataObject('管理部门')"
                      :selectData="formData.manageDepartmentId"
                    />
                    <span v-else>{{ formData.manageDepartmentName }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="管理人" prop="assetManagerId">
                    <el-select
                      style="width: 100%"
                      v-if="!props.isReadonly"
                      v-model="formData.assetManagerId"
                      placeholder="请选择管理人"
                      clearable
                      @change="(e) => changePerson(e, '管理人')"
                    >
                      <el-option
                        v-for="item in personList"
                        :label="`${item.firstName}`"
                        :value="`${item.id}`"
                      />
                    </el-select>

                    <span v-else>{{ formData.assetManagerName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="使用日期" prop="usingDate">
                    <el-date-picker
                      v-if="!props.isReadonly"
                      v-model="formData.usingDate"
                      type="date"
                      placeholder="请选择使用日期"
                      format="YYYY/MM/DD"
                      value-format="YYYY-MM-DD"
                    />

                    <span v-else>{{
                      formData.usingDate
                        ? dayjs(formData.usingDate).format("YYYY-MM-DD")
                        : ""
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row></el-tab-pane
            >
            <el-tab-pane label="其他信息">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="到货日期" prop="arrivalDate">
                    <el-date-picker
                      style="width: 300px"
                      v-if="!props.isReadonly"
                      v-model="formData.arrivalDate"
                      type="date"
                      placeholder="请选择到货日期"
                      format="YYYY/MM/DD"
                      value-format="YYYY-MM-DD"
                    />

                    <span v-else>{{
                      formData.arrivalDate
                        ? dayjs(formData.arrivalDate).format("YYYY-MM-DD")
                        : ""
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="器具附件"
              ><el-row class="ml-[15px]">
                <CommonUploadFile
                  :isRead="props.isReadonly"
                  :files="formData.assetPhotos"
                  @update-files="updateFormFiles"
                />

                <!-- <image-id></image-id> -->

                <!-- <el-input
                    v-model="formData.assetPhotos"
                    style="display: none"
                  ></el-input> -->
              </el-row></el-tab-pane
            >
          </el-tabs>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import dayjs from "dayjs";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMASSETINFOEDIT",
  inheritAttrs: false,
});
// 定义上传图片文件夹名
const fileName = ref("mtAssetInfo");
const emit = defineEmits(["reset-table", "change-visible"]);
// 图片地址
const actionUrl = import.meta.env.VITE_APP_UPLOAD_URL;
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetTypeIdTree: {
    type: String,
    default: () => {
      return "";
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (props.assetTypeIdTree) {
      formData.assetTypeId = props.assetTypeIdTree;
      catalogList.value.forEach((item) => {
        if (item.id == props.assetTypeIdTree) {
          formData.assetTypeName = item.assetTypeName;
          formData.assetTypeCode = item.assetTypeCode;
          return;
        } else {
          if (item.nodes.length > 0) {
            catalogList1(item.nodes);
          }
        }
      });
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const catalogList1 = (item) => {
  if (item.length > 0) {
    item.forEach((item1) => {
      if (item1.id == props.assetTypeIdTree) {
        formData.assetTypeName = item1.assetTypeName;
        formData.assetTypeCode = item1.assetTypeCode;
        return;
      } else {
        catalogList1(item1.nodes);
      }
    });
  }
};

const rules = reactive({
  version: [],
  assetCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
    { required: true, message: "请输入检具编号", trigger: "blur" },
  ],
  assetName: [
    { required: true, message: "请输入器具名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  assetKind: [],
  assetTypeId: [
    { required: true, message: "请选择器具类型", trigger: "change" },
  ],
  assetBrandId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  assetBrandName: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  assetModelId: [
    { required: true, message: "请选择品牌型号", trigger: "change" },
  ],
  assetModelNo: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  // assetSpecification: [
  //   { required: true, message: "请输入规格/型号", trigger: "blur" },
  //   { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  // ],
  assetStatus: [
    { required: true, message: "请选择器具状态", trigger: "change" },
  ],
  assetQuantity: [],
  quantityUnit: [
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
  ],
  makerId: [{ required: true, message: "请选择制造工厂", trigger: "change" }],
  manufactureCode: [
    { required: true, message: "请输入出厂编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  supplierId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  arrivalDate: [],
  fixedAssetCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  assetLifespan: [
    {
      message: "请输入器具寿命",
      trigger: "blur",
      pattern: /^([0-9]{1,2}|100)$/,
    },
  ],
  originalValue: [
    {
      message: "请输入资产原值8位整数2位小数",
      trigger: "blur",
      validator: validator1,
    },
  ],
  residualValue: [
    {
      message: "请输入资产折旧价值8位整数2位小数",
      trigger: "blur",
      validator: validator1,
    },
  ],
  manageDepartmentId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  manageDepartmentName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  assetManagerId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  assetManagerName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  usingDepartmentId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  usingDepartmentName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  usingPersonId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  usingPersonName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  usingDate: [],
  repairDepartmentId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  repairDepartmentName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  repairManagerId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  repairManagerName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  locationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  locationName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  installLocationExplain: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  checkPeriod: [
    {
      message: "请输入检定周期",
      trigger: "blur",
      pattern: /^([0-9]{1,2}|100)$/,
    },
  ],
  prevCheckDate: [],
  nextCheckDate: [],
  checkPlace: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  checkPerson: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  measuringAccuracy: [
    {
      trigger: "blur",
      validator: validator,
    },
  ],
  accuracyLevel: [
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  measuringDivision: [
    {
      trigger: "blur",
      validator: validator,
    },
  ],
  headerNumber: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  orderNumber: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  drawingNumber: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  assetSpecification: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  measuringRange: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  assetAttribute1: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  accountDate: [],
  enabled: [],
  deleted: [],
  organizationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});
function validator(rule, value, callback: (a?: any) => {}) {
  if (!value) {
    //先判断空可以过
    // callback(new Error("请输入2位整数3位小数"));
    return true;
  } else {
    if (/^\d{1,2}(\.\d{0,3})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入2位整数3位小数"));
    }
  }
}

function validator1(rule, value, callback: (a?: any) => {}) {
  if (!value) {
    //先判断空可以过
    // callback(new Error("请输入8位整数2位小数"));

    return true;
  } else {
    if (/^\d{1,8}(\.\d{0,2})?$/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入8位整数2位小数"));
    }
  }
}

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  assetCode: "",
  assetName: "",
  assetKind: "",
  assetTypeId: "",
  assetTypeCode: "",
  assetTypeName: "",
  assetBrandId: "",
  assetBrandName: "",
  assetModelId: "",
  assetModelNo: "",
  assetSpecification: "",
  headerNumber: "",
  orderNumber: "",
  drawingNumber: "",
  assetStatus: "",
  assetQuantity: "",
  quantityUnit: "",
  makerId: "",
  makerName: "",
  makerCode: "",
  manufactureCode: "",
  supplierId: "",
  supplierCode: "",
  supplierName: "",
  arrivalDate: "",
  fixedAssetCode: "",
  isFixedAsset: 0,
  assetLifespan: "",
  originalValue: "",
  residualValue: "",
  manageDepartmentId: "",
  manageDepartmentName: "",
  assetManagerId: "",
  assetManagerName: "",
  usingDepartmentId: "",
  usingDepartmentName: "",
  usingPersonId: "",
  usingPersonName: "",
  usingDate: "",
  repairDepartmentId: "",
  repairDepartmentName: "",
  repairManagerId: "",
  repairManagerName: "",
  locationId: "",
  locationName: "",
  installLocationExplain: "",
  checkPeriod: "",
  prevCheckDate: "",
  nextCheckDate: "",
  checkPlace: "",
  checkPerson: "",
  measuringAccuracy: "",
  measuringDivision: "",
  measuringRange: "",
  assetAttribute1: "",
  remarks: "",
  accountDate: "",
  enabled: "",
  deleted: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  measuringType: "",
  assetPhotos: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        assetCode,
        assetName,
        assetKind,
        assetTypeId,
        assetTypeCode,
        assetTypeName,
        assetBrandId,
        assetBrandName,
        assetModelId,
        assetModelNo,
        assetSpecification,
        headerNumber,
        orderNumber,
        drawingNumber,
        assetStatus,
        assetQuantity,
        quantityUnit,
        makerId,
        makerName,
        makerCode,
        manufactureCode,
        supplierId,
        supplierCode,
        supplierName,
        arrivalDate,
        fixedAssetCode,
        isFixedAsset,
        assetLifespan,
        originalValue,
        residualValue,
        manageDepartmentId,
        manageDepartmentName,
        assetManagerId,
        assetManagerName,
        usingDepartmentId,
        usingDepartmentName,
        usingPersonId,
        usingPersonName,
        usingDate,
        repairDepartmentId,
        repairDepartmentName,
        repairManagerId,
        repairManagerName,
        locationId,
        locationName,
        installLocationExplain,
        checkPeriod,
        prevCheckDate,
        nextCheckDate,
        checkPlace,
        checkPerson,
        measuringAccuracy,
        accuracyLevel,
        measuringDivision,
        measuringRange,
        assetAttribute1,
        remarks,
        accountDate,
        enabled,
        deleted,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        measuringType,
        assetPhotos,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetCode,
        assetName,
        assetKind,
        assetTypeId,
        assetTypeCode,
        assetTypeName,
        assetBrandId,
        assetBrandName,
        assetModelId,
        assetModelNo,
        assetSpecification,
        headerNumber,
        orderNumber,
        drawingNumber,
        assetStatus,
        assetQuantity,
        quantityUnit,
        makerId,
        makerName,
        makerCode,
        manufactureCode,
        supplierId,
        supplierCode,
        supplierName,
        arrivalDate,
        fixedAssetCode,
        isFixedAsset,
        assetLifespan,
        originalValue,
        residualValue,
        manageDepartmentId,
        manageDepartmentName,
        assetManagerId,
        assetManagerName,
        usingDepartmentId,
        usingDepartmentName,
        usingPersonId,
        usingPersonName,
        usingDate,
        repairDepartmentId,
        repairDepartmentName,
        repairManagerId,
        repairManagerName,
        locationId,
        locationName,
        installLocationExplain,
        checkPeriod,
        prevCheckDate,
        nextCheckDate,
        checkPlace,
        checkPerson,
        measuringAccuracy,
        accuracyLevel,
        measuringDivision,
        measuringRange,
        assetAttribute1,
        remarks,
        accountDate,
        enabled,
        deleted,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        measuringType,

        assetPhotos: assetPhotos ?? [],
      });
      formData.assetStatus = String(formData.assetStatus);
      //  编辑时获取品牌型号数据
      handleMakerChange(formData.makerId);
      //  编辑时根据管理部门id获取管理人数据
      changeDept(formData.manageDepartmentId, "管理部门");
      //  编辑时根据检定/校准部门id获取检定/校准负责人数据
      changeDept(formData.repairDepartmentId, "检定/校准部门");
      //  编辑时根据使用部门id获取使用人数据
      changeDept(formData.usingDepartmentId, "使用部门");
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.assetCode = "";
  formData.assetName = "";
  formData.assetKind = "";
  formData.assetTypeId = "";
  formData.assetTypeCode = "";
  formData.assetTypeName = "";
  formData.assetBrandId = "";
  formData.assetBrandName = "";
  formData.assetModelId = "";
  formData.assetModelNo = "";
  formData.assetSpecification = "";
  formData.headerNumber = "";
  formData.orderNumber = "";
  formData.drawingNumber = "";
  formData.assetStatus = "";
  formData.assetQuantity = "";
  formData.quantityUnit = "";
  formData.makerId = "";
  formData.makerName = "";
  formData.makerCode = "";
  formData.manufactureCode = "";
  formData.supplierId = "";
  formData.supplierCode = "";
  formData.supplierName = "";
  formData.arrivalDate = "";
  formData.fixedAssetCode = "";
  formData.isFixedAsset = 0;
  formData.assetLifespan = "";
  formData.originalValue = "";
  formData.residualValue = "";
  // 管理部门
  formData.manageDepartmentId = "";
  formData.manageDepartmentName = "";
  // 管理人
  formData.assetManagerId = "";
  formData.assetManagerName = "";
  // 使用部门
  formData.usingDepartmentId = "";
  formData.usingDepartmentName = "";
  // 使用人
  formData.usingPersonId = "";
  formData.usingPersonName = "";
  formData.usingDate = "";
  // 检定/校准部门
  formData.repairDepartmentId = "";
  formData.repairDepartmentName = "";
  // 检定/校准负责人
  formData.repairManagerId = "";
  formData.repairManagerName = "";
  //
  formData.locationId = "";
  formData.locationName = "";
  formData.installLocationExplain = "";
  formData.checkPeriod = "";
  formData.prevCheckDate = "";
  formData.nextCheckDate = "";
  formData.checkPlace = "";
  formData.checkPerson = "";
  formData.measuringAccuracy = "";
  formData.accuracyLevel = "";
  formData.measuringDivision = "";
  formData.measuringRange = "";
  formData.assetAttribute1 = "";
  formData.remarks = "";
  formData.accountDate = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.organizationId = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.measuringType = "";
  personList.value = [];
  personList1.value = [];
  personList2.value = [];
  formData.assetPhotos = [];
}

const loading = ref(false);

/** 资产台账保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // 根据制造工厂id赋值制造工厂名称
      makerList.value.forEach((item) => {
        if (item.id == formData.makerId) {
          formData.makerName = item.makerName;
          formData.makerCode = item.makerCode;
        }
      });

      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/mtAssetInfo/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/mtAssetType/getAvailableTree",
    method: "POST",
    data: {},
  }).then((res) => {
    catalogList.value = res.data;
    console.log(catalogList.value);
  });
};

// 获取制造工厂列表
const makerList: any = ref([]);
const getMakerList = async () => {
  request({
    url: `/eam/eammaker/getList`,
    method: "post",
    data: { assetKind: "2" },
  })
    .then((res) => {
      makerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

// 获取供应商列表
const mdmpartnerList: any = ref([]);
const getPartnerList = async () => {
  request({
    url: `mdm/mdmpartner/getListByFull`,
    method: "post",
    data: {},
  })
    .then((res) => {
      mdmpartnerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

// 点击供应商 获取name
const handelPartner = (e) => {
  if (e) {
    mdmpartnerList.value.forEach((item) => {
      if (item.id == e) {
        formData.supplierName = item.partnerName;
        formData.supplierCode = item.partnerCode;
      }
    });
  } else {
    formData.supplierName = "";
    formData.supplierCode = "";
  }
};
//  获取器具型号列表
const assetNoList: any = ref([]);
const getAssetNoList = async () => {
  request({
    url: `/eam/mtAssetmodel/getList`,
    method: "post",
    data: {},
  })
    .then((res) => {
      assetNoList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (item == "管理部门") {
    formData.assetManagerId = "";
    formData.assetManagerName = "";
    formData.manageDepartmentId = ids;
    personList.value = [];
    changeDept(ids, item);
  }
  if (item == "检定/校准部门") {
    formData.repairManagerId = "";
    formData.repairManagerName = "";
    formData.repairDepartmentId = ids;
    personList1.value = [];
    changeDept(ids, item);
  }
  if (item == "使用部门") {
    formData.usingPersonId = "";
    formData.usingPersonName = "";
    formData.usingDepartmentId = ids;
    personList2.value = [];
    changeDept(ids, item);
  }
}
/** 选择组织机构并赋值Name   start **/
function getSelectDatas(datas: any, item: any) {
  if (item == "管理部门") {
    formData.manageDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
  if (item == "检定/校准部门") {
    formData.repairDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
  if (item == "使用部门") {
    formData.usingDepartmentName = datas.organizationName
      ? datas.organizationName
      : "";
  }
}
// 组织机构 placeholder值
const dataObject = (item: string) => {
  return {
    name:
      item == "管理部门"
        ? "管理部门"
        : item == "使用部门"
        ? "使用部门"
        : "检定/校准部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
// 点击组织机构 选择人员
const personList = ref([]);
const personList1 = ref([]);
const personList2 = ref([]);

const changeDept = async (id, name) => {
  if (id) {
    const res = await request({
      url: "/system/sysUser/getList ",
      method: "post",
      data: {
        departmentId: id,
      },
    });

    if (name == "管理部门") {
      personList.value = res.data;
    }
    if (name == "检定/校准部门") {
      personList1.value = res.data;
    }
    if (name == "使用部门") {
      personList2.value = res.data;
      console.log("人员", res.data);
    }
  }
};

// 人员改变时
const changePerson = (e: any, name: string) => {
  if (e) {
    if (name == "管理人") {
      personList.value.forEach((item: any) => {
        if (item.id == e) {
          formData.assetManagerName = item.firstName;
        }
      });
    }
    if (name == "检定/校准负责人") {
      personList1.value.forEach((item: any) => {
        if (item.id == e) {
          formData.repairManagerName = item.firstName;
        }
      });
    }
    if (name == "使用人") {
      personList2.value.forEach((item: any) => {
        if (item.id == e) {
          formData.usingPersonName = item.firstName;
        }
      });
    }
  } else {
    if (name == "管理人") {
      formData.assetManagerId = "";
      formData.assetManagerName = "";
    }
    if (name == "检定/校准负责人") {
      formData.repairManagerId = "";
      formData.repairManagerName = "";
    }
    if (name == "使用人") {
      formData.usingPersonId = "";
      formData.usingPersonName = "";
    }
  }
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

// 点击位置树
const changeLocation = (e) => {
  if (e) {
    formData.locationId = e.id;
    formData.locationName = e.locationName;
  } else {
    formData.locationId = "";
    formData.locationName = "";
  }
};

const handelLocation = (e) => {
  if (!e) {
    formData.locationId = "";
    formData.locationName = "";
  }
};

// 点击制造工厂 返回品牌和型号
const brandModelList = ref([]);
const handleMakerChange = async (e, item) => {
  if (item == "row") {
    formData.assetBrandId = "";
    formData.assetBrandName = "";
    formData.assetModelId = "";
    formData.assetModelNo = "";
  }
  if (e) {
    brandModelList.value = [];
    // formData.assetModelId = "";
    const { data } = await request({
      url: "/eam/mtAssetmodel/getList",
      method: "POST",
      data: {
        makerId: e,
        assetKind: "2",
      },
    });

    brandModelList.value = data;
  } else {
    formData.assetModelId = "";
    formData.makerId = "";
    formData.makerName = "";
    brandModelList.value = [];
  }
};

// 点击品牌 赋值
const handelBrandModelNo = (e) => {
  if (e) {
    brandModelList.value.forEach((item) => {
      if (item.id == e) {
        formData.assetBrandId = item.brandId;
        formData.assetBrandName = item.brandName;
        formData.assetModelId = item.id;
        formData.assetModelNo = item.modelNo;
      }
    });
  } else {
    formData.assetBrandId = "";
    formData.assetBrandName = "";
    formData.assetModelId = "";
    formData.assetModelNo = "";
  }
};
// 点击器具类型树子节点赋值器具类型名称
const handleNodeClick = (e) => {
  if (e) {
    formData.assetSpecification = e?.assetSpecification || "";
    formData.assetTypeName = e.assetTypeName;
    formData.assetTypeCode = e.assetTypeCode;
  } else {
    formData.assetTypeName = "";
    formData.assetTypeCode = "";
    formData.assetSpecification = "";
  }
};
// 图片处理
function updateFormFiles(val: []) {
  console.log(val);

  formData.assetPhotos = val;
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
onMounted(() => {
  getCAtalogList();
  getAssetNoList();
  getMakerList();
  getPartnerList();
  getLocationInfoTree();
});
</script>
